package com.zp.testpractice.other.contract;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zp.testpractice.ALog;
import com.zp.testpractice.R;

import org.json.JSONException;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

/**
 * @author izp on 2017/11/12.
 */

public class ContractTestFragment extends Fragment {
    @BindView(R.id.showResult)
    TextView showResult;
    @BindView(R.id.action)
    Button action;
    @BindView(R.id.action2)
    Button action2;

    Unbinder unbinder;

    private Activity activity;
    private ContactUtils contactUtils;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
        contactUtils = new ContactUtils(activity);
    }
    public static ContractTestFragment getInstance(){
        return new ContractTestFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contract_test, null);
        unbinder = ButterKnife.bind(this, view);
        action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toContacts();

            }
        });
        action2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(intent,1000);

            }
        });
        return view;
    }

    private void toContacts(){
        AndPermission.with(activity).requestCode(100)
                .permission(Permission.CONTACTS)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 此对话框可以自定义，调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(activity, rationale).show();
                    }
                })
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
//                        fetchContactInformation();
//                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                        startActivityForResult(intent,1001);
//                        contactUtils.queryContactByPhone("15736096668");
//
//                        contactUtils.addNewContact("郑威","18702324688","630044906@qq.com");
//                        contactUtils.queryContactByName("郑威");
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

                    }
                }).start();
    }

    private void showResult(String...contract){
        StringBuilder stringBuilder = new StringBuilder();
        for (String str:contract){
            stringBuilder.append(str).append(";");
        }
        showResult.setText(stringBuilder.toString());
    }
    private void showResult(String str){
        showResult.setText(str);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode==1000){
            if (resultCode==RESULT_OK){
                if (data!=null){
                    Uri uri=data.getData();
                    getContactData(uri);
//                    String[] contact=getPhoneContacts(uri);
//                    String[] contact=getContactData2(uri);
//                    if (contact!=null){
//                        showResult(contact);
//                    }
                }
            }
        }
        if (requestCode==1001){
            if (resultCode==RESULT_OK){
                if (data!=null){
                    Uri uri=data.getData();
//                    获取所选联系人的所有信息
//                    getContactData(uri);
//                    根据获取的联系人的 id 更新联系人信息
//                    contactUtils.updateContact(getContactData(uri)[6],"luyan@jd.com");
//                    根据获取的联系人id 尝试删除联系人
                    contactUtils.deleteContactData(getContactData(uri)[6]);
//                    String[] contact=getPhoneContacts(uri);
//                    String[] contact=getContactData2(uri);
//                    if (contact!=null){
//                        showResult(contact);
//                    }
                }
            }
        }
    }
    private String[] getContactData(Uri uri){
        ALog.d("uri:"+uri.toString());
        //得到ContentResolver对象
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        String id = null,name = null,phoneNumber = null,email = null,note = null,company = null,title = null;
        if (cursor.moveToFirst()) {
//            id=cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
            id=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
            name=cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
            ALog.d("id="+id+" name="+name);
            //Fetch Phone Number
            Cursor phoneCursor = cr.query(
                    android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id,
                    null, null);
            while(phoneCursor.moveToNext()) {
                phoneNumber = phoneCursor.getString(
                        phoneCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
                ALog.d("id="+id+" name="+name+" phoneNumber="+phoneNumber);
            }
            phoneCursor.close();
            //Fetch email
            Cursor emailCursor = cr.query(
                    android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null, android.provider.ContactsContract.CommonDataKinds.Email.CONTACT_ID+"="+id,
                    null, null);
            while(emailCursor.moveToNext()) {
                email = emailCursor.getString(
                        emailCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Email.DATA));
                ALog.d("id="+id+" name="+name+" email="+email);
            }
            emailCursor.close();
            //Fetch note
            Cursor noteCursor = cr.query(
                    ContactsContract.Data.CONTENT_URI,
                    new String[] { ContactsContract.Contacts.Data._ID, ContactsContract.CommonDataKinds.Note.NOTE },
                    ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
                            + ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE + "'",
                    new String[] { id }, null);
            while(noteCursor.moveToNext()) {
                note = noteCursor.getString(
                        noteCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Email.DATA));
                ALog.d("id="+id+" name="+name+" note="+note);
            }
            noteCursor.close();

            //Fetch organization
            Cursor organizationCursor = cr.query(
                    ContactsContract.Data.CONTENT_URI,
                    new String[] { ContactsContract.Data._ID, ContactsContract.CommonDataKinds.Organization.COMPANY,
                            ContactsContract.CommonDataKinds.Organization.TITLE },
                    ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
                            + ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE + "'",
                    new String[] { id }, null);
            while(organizationCursor.moveToNext()) {
                company = organizationCursor.getString(
                        organizationCursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
                title = organizationCursor.getString(
                        organizationCursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                ALog.d("id="+id+" name="+name+" company="+company+" title="+title);
            }
            organizationCursor.close();
        }
        cursor.close();
        return new String[]{name,phoneNumber,email,company,title,note,id};
    }
    public void fetchContactInformation() {
        String id,name,phoneNumber,email;
        ContentResolver contentResolver = activity.getContentResolver();
        Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        while(cursor.moveToNext()) {
            id=cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
            name=cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));

            //Fetch Phone Number
            Cursor phoneCursor = contentResolver.query(
                    android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id,
                    null, null);
            while(phoneCursor.moveToNext()) {
                phoneNumber = phoneCursor.getString(
                        phoneCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
                ALog.d("id="+id+" name="+name+" phoneNumber="+phoneNumber);
            }
            phoneCursor.close();

            //Fetch email
            Cursor emailCursor = contentResolver.query(
                    android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null, android.provider.ContactsContract.CommonDataKinds.Email.CONTACT_ID+"="+id,
                    null, null);
            while(emailCursor.moveToNext()) {
                email = emailCursor.getString(
                        emailCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Email.DATA));
                ALog.d("id="+id+" name="+name+" email="+email);
            }
            emailCursor.close();
        }
        cursor.close();
    }

    /**
     * 读取联系人信息
     * @param uri
     */
    private String[] getContactData2(Uri uri){
        String[] contact = new String[6];
        //得到ContentResolver对象
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null&&cursor.moveToFirst()) {
            //取得联系人姓名
            int contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            //获取 id 所在列的索引
            String contactId = cursor.getString(contactIdIndex);
            //联系人id
//            String mimetype = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.Data.MIMETYPE));

            contact[0] = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contact[1]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            contact[2]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));

            contact[3]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT));
            contact[4]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
            contact[5]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    /**
     * 读取联系人信息
     * @param uri
     */
    private String[] getPhoneContacts(Uri uri){
        String[] contact = new String[6];
        //得到ContentResolver对象
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null&&cursor.moveToFirst()) {
            //取得联系人姓名
            int contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            //获取 id 所在列的索引
            String contactId = cursor.getString(contactIdIndex);
            //联系人id
            String mimetype = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.Data.MIMETYPE));

            contact[0] = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mimetype)) {
                int phoneType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                contact[1]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contact[2]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
//                contact[2]="为毛不是邮箱";
//                contact[2]=getContactEmail(contactId);
//                ALog.d(getContactEmail(contactId));
            }

            if (ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE.equals(mimetype)) {
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE)) ==
                        ContactsContract.CommonDataKinds.Organization.TYPE_CUSTOM) {
                    contact[3]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT));
                    contact[4]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                }
            }
            if (ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE.equals(mimetype)) {
                contact[5]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
            }
//            contact[5] = getData1(cr,contactId,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    private String getContactEmail(String contactId){
        ALog.d("contactId:"+contactId);
        // 获取该联系人邮箱
        Cursor emails = activity.getContentResolver().query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                        + " = " + contactId,null ,null );
        StringBuilder stringBuilder = new StringBuilder();
        if (null!=emails && emails.moveToFirst()) {
            do {
                // 遍历所有的电话号码
                String emailType = emails
                        .getString(emails
                                .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                String emailValue = emails
                        .getString(emails
                                .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                ALog.d("emailType", emailType);
                ALog.d("emailValue", emailValue);
                stringBuilder.append(emailType).append("--").append(emailValue).append(";");
            } while (emails.moveToNext());
            emails.close();
        }else {
            ALog.d("Cursor:emailCursor是空的");
        }
        return stringBuilder.toString();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
